<?php
/**
 * Created by 项目.
 * User: xuguopeng
 * Date: 2020-04-02
 * Time: 01:55
 */

namespace app\api\controller\v1;

use app\api\model\HotelRoom;
use app\api\model\UserCollection;
use app\api\service\Token as TokenService;
use app\lib\exception\ParameterException;

class Collection
{
    /**
     * 收藏与取消收藏
     */
    public function changeCollection($hotel_room_id)
    {
        $uid = TokenService::getCurrentUid();
        $info = UserCollection::where('user_id',$uid)
            ->where('hotel_room_id',$hotel_room_id)->find();
        if($info) {
            UserCollection::destroy($info['id']);
            return writeJson(202, [], '取消成功');
        } else {
            $subject = HotelRoom::where('id',$hotel_room_id)->find();
            if($subject) {
                UserCollection::create([
                    'user_id' => $uid,
                    'hotel_room_id' => $hotel_room_id,
                ]);
                return writeJson(202, [], '收藏成功');
            } else {
                throw new ParameterException([
                    'msg' => [
                        'collection' => '没有此房间'
                    ]
                ]);
            }
        }
    }
    /**
     * 获取收藏状态
     */
    public function getCollectionStatus($hotel_room_id)
    {
        $uid = TokenService::getCurrentUid();
        $info = UserCollection::where('user_id',$uid)
            ->where('hotel_room_id',$hotel_room_id)->find();
        if($info) {
            return writeJson(200, ['isValid'=>true], '已收藏');
        } else {
            return writeJson(200, ['isValid'=>false], '未收藏');
        }
    }

    /**
     * 获取收藏列表
     */
    public function getCollectionList()
    {
        $uid = TokenService::getCurrentUid();
        $list = UserCollection::where('user_id', $uid)->with([
            'hotelRoom' => [
                'imgs' => ['img'], 'admin', 'roomTag'
            ]
        ])->select()->toArray();
        return $list;
    }
}